package com.sun.service.impl;

import com.sun.dto.GoodsSalesDTO;
import com.sun.entity.Orders;
import com.sun.mapper.OrderMapper;
import com.sun.mapper.UserMapper;
import com.sun.service.ReportService;
import com.sun.service.WorkspaceService;
import com.sun.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 根据时间区间统计营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        //1.创建一个用来存储日期的列表,将开始的时间添加到列表中
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        //2.通过循环,从开始的日期时间往后推算,直到到达结束的日期,每次将下一天的日期都添加到日期列表中
        while (!begin.equals(end)){
            //日期计算,获取指定日期后1天的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //3.创建一个用来存储营业额数据的列表
        List<Double> turnoverList = new ArrayList<>();
        //4.遍历日期列表中的每个日期
        for (LocalDate date : dateList) {
            // 封装当前的起始时(当天的0点0分0秒)
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            // 封装当前的结束时间(当天的23点59分59秒)
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 创建一个集合,用来存储查询条件的相关数据
            Map<String,Object> map = new HashMap<>();
            // 封装在查询条件中设置订单状态为已完成的
            map.put("status", Orders.COMPLETED);
            // 在查询条件中设置起始时间
            map.put("begin", beginTime);
            //在查询条件中设置结束时间
            map.put("end", endTime);

            //通过订单的映射器(orderMapper) ,根据给定的条件进行做计算营业额
            Double turnover = orderMapper.sumByMap(map);
            //如果计算出来的营业额为null, 就设置值为0.0
            turnover = turnover == null ? 0.0 : turnover;
            //将当前日期对应的营业额添加到营业额列表中
            turnoverList.add(turnover);
        }

        //将日期列表转换为以逗号分隔的字符串形式
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 统计指定时间去年内的用户数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 1.新建一个用来存储日期的列表
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        // 2.通过循环,从开始的日期时间往后推算,直到到达结束的日期,每次将下一天的日期都添加到日期列表中
        while (!begin.equals(end)){
            //日期计算,获取指定日期后1天的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 3.创建一个用来存储每日新增用户数量
        ArrayList<Integer> newUserList = new ArrayList<>();
        // 4.创建一个用来存储总用户数量
        ArrayList<Integer> totalUserList = new ArrayList<>();

        // 5.遍历前面构建好的日期列表
        for (LocalDate date : dateList) {
            // 封装当前的起始时(当天的0点0分0秒)
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            // 封装当前的结束时间(当天的23点59分59秒)
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 获取新增用户数量
            Integer newUser = getUserCount(beginTime,endTime);
            // 获取总用户数量
            Integer totalUser = getUserCount(null, endTime);

            // 将当前日期对应的新增用户数量添加到新增用户列表中
            newUserList.add(newUser);
            // 将当前日期对应的总用户数量添加到对应的集合
            totalUserList.add(totalUser);
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 根据时间区间统计订单数量
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //定义存储时间的集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //每天订单总数集合
        List<Integer> orderCountList = new ArrayList<>();
        //每日有效订单数
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //查询每天的总订单数
            //select count(id) from orders where order_time > ? and order_time < ? and status = ?
            Integer totalOrderCount = getOrderCount(beginTime,endTime,null);
            //查询每天的有效订单数
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);


            orderCountList.add(totalOrderCount);
            validOrderCountList.add(validOrderCount);
        }

        //时间区间内的总订单数 -- 方法引用
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的总的有效订单数 -- 方法引用
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount.doubleValue();
        }


        return  OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询指定时间区间内的销量排名top10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //构建开始和结束的时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //从orderMapper中获取销量排名前10名的商品销售数据
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime,endTime);

        //拼接商品销售数量列表字符串
        String nameList = StringUtils.join(
                goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect((Collectors.toList())),
                ",");

        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),
                ",");
        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 生成运营数据报表
     * template文件夹,存储模板文件
     *  - excel模板文件(xlsx / xls)
     *  - word模板文件(.docx)
     *  - Thymeleaf模板文件(.html)
     *
     * @param response
     */
    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(
                LocalDateTime.of(dateBegin, LocalTime.MIN),
                LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader()
                .getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(
                        LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据时间区间统指定状态的订单数量
     * @param beginTime
     * @param endTime
     * @return
     */
    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime,Integer status) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", status);

        return orderMapper.countByMap(map);
    }

    /**
     * 根据时间区间统计用户的数量
     * @param begin
     * @param end
     * @return
     */
    private Integer getUserCount(LocalDateTime begin, LocalDateTime end) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);

        return userMapper.countByMap(map);
    }


}
